package com.fowo.api.sys.service.impl;

import com.fowo.api.sys.config.FileServiceProperties;
import com.fowo.api.sys.service.FileStorageService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * 本地文件存储服务
 */
@Service
@ConditionalOnProperty("file-service.local-dir")
@EnableConfigurationProperties(FileServiceProperties.class)
public class LocalFileStorageServiceImpl implements FileStorageService {

    @Resource
    private FileServiceProperties serviceProperties;

    @Override
    public String write(String filename, boolean useFilenameAsKey, InputStream inputStream) throws Exception  {
        String storageKey = useFilenameAsKey ? filename : createStorageKey(filename);
        File file = getFile(storageKey);
        try(FileOutputStream outputStream = new FileOutputStream(file)) {
            StreamUtils.copy(inputStream, outputStream);
        }
        return storageKey;
    }

    @Override
    public InputStream read(String storageKey) throws Exception {
        File file = getFile(storageKey);
        return new FileInputStream(file);
    }

    @Override
    public void delete(String storageKey) throws Exception {
        File file = getFile(storageKey);
        if (file.exists()) {
            file.delete();
        }
    }

    private File getFile(String storageKey) {
        return new File(serviceProperties.getLocalDir(), storageKey);
    }
}
